package com.moneyhelper.upms.rest;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.moneyhelper.common.resp.RestResponse;
import com.moneyhelper.common.rest.CommonRest;
import com.moneyhelper.upms.biz.SysUserBiz;
import com.moneyhelper.upms.constant.RedisKey;
import com.moneyhelper.upms.constant.TokenConstant;
import com.moneyhelper.upms.dto.FrontUserInfo;
import com.moneyhelper.upms.entity.SysMenu;
import com.moneyhelper.upms.entity.SysUser;
import com.moneyhelper.upms.handler.ContextHandler;
import com.moneyhelper.upms.rest.dto.SysUserSaveDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author： ygl
 * @date： 2019/06/30
 * @Description：
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserRest extends CommonRest<SysUserBiz, SysUser, String> {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/login")
    public RestResponse login(@RequestBody SysUser model){
        String username = model.getUsername();
        String password = model.getPassword();
        SysUser user = new SysUser();
        user.setUsername(StrUtil.blankToDefault(username,""));
        user.setPassword(StrUtil.blankToDefault(password,""));
        SysUser sysUser = biz.selectOne(user);
        if (sysUser == null) {
            return RestResponse.ERROR("用户名或者密码错误");
        }
        String token = RandomUtil.randomString(10);
        stringRedisTemplate.opsForValue().set(RedisKey.userToken+token,sysUser.getId(),2L, TimeUnit.HOURS);
        return RestResponse.OK(token);
    }

    @PostMapping("/logout")
    public RestResponse logout(@RequestBody Map<String,String> params){
        String token = params.get(TokenConstant.tokenName);
        stringRedisTemplate.delete(RedisKey.userToken+token);
        return RestResponse.OK();
    }


    @GetMapping("/{id}/role")
    public RestResponse getRole(@PathVariable String id){
        List<String> roleIds = biz.getRoleIds(id);
        return RestResponse.OK(roleIds);
    }

    @PostMapping("/{id}/role")
    public RestResponse updateRole(@PathVariable String id,@RequestBody Map<String,String[]> params){
        String[] roleIds = params.get("roleIds");
        biz.updateRole(id,roleIds);
        return RestResponse.OK();
    }


    @GetMapping("/info")
    public RestResponse info(){
        String userId = ContextHandler.getUserId();
        return RestResponse.OK(biz.getUserInfoUserId(userId));
    }

}
